<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      error: ''
    };
  },
  methods: {
    login() {
      try {
        axios.post('/user/login', this.user)
            .then(response => {
              // 根据你的后端API返回的token或其他验证信息，进行后续处理
              // 比如保存token到localStorage或Vuex，并重定向到首页
              const token = response.data.token; // 假设后端返回了token
              localStorage.setItem('token', token);
              this.$router.push('/front/home'); // 登录成功后重定向到首页
            })
            .catch(error => {
              this.error = error.response.data.message || '登录失败，请重试';
            });
      } catch (error) {
        this.error = '登录时发生错误，请稍后再试';
      }
    }
  }
};

</script>

<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="login" class="form">
      <div class="form-group">
        <label for="username">用户名</label>
        <input v-model="user.username" required type="text"/>
      </div>
      <div class="form-group">
        <label for="password">密 &nbsp; 码</label>
        <input v-model="user.password" required type="password"/>
      </div>
      <div style="display: flex;width: 200px;margin: auto">
        <button type="submit" class="login-button">登录</button>
      </div>
    </form>
    <p v-if="error">{{ error }}</p>
    <p><router-link to="/front/register">没有账号？注册</router-link></p>
  </div>
</template>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.login-container h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.form-group input {
  width: calc(100% - 22px); /* Subtract padding and border width */
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  color: #333;
}

.login-button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  color: #fff;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover {
  background-color: #369a6f;
}

p {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

p a {
  color: #42b983;
  text-decoration: none;
  transition: color 0.3s;
}

p a:hover {
  color: #369a6f;
}

.error {
  color: red;
  text-align: center;
  margin-top: 10px;
}
</style>
